package com.xiangyang.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xiangyang.entity.dto.Result;
import com.xiangyang.exception.CustomerAuthenticationException;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        ServletOutputStream out = response.getOutputStream();
        String messageString="";
        int code = 508;
        if (exception instanceof AccountExpiredException){
            messageString="用户过期，登录失败";
        }else if (exception instanceof BadCredentialsException){
            messageString="用户名或密码错误，请重新输入";
        } else if (exception instanceof CredentialsExpiredException) {
            messageString="密码过期，登录失败";
        } else if (exception instanceof DisabledException) {
            messageString="用户被禁用，登录失败";
        } else if (exception instanceof LockedException) {
            messageString="账户被封禁，登录失败";
        } else if (exception instanceof InternalAuthenticationServiceException) {
            messageString="账户不存在，登录失败";
        } else if (exception instanceof CustomerAuthenticationException) {
            messageString=exception.getMessage();
            code=608;
        }else {
            messageString="登录失败";
        }
        String message = JSON.toJSONString(Result.error(code,messageString), SerializerFeature.DisableCircularReferenceDetect);
        out.write(message.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}
